package com.example.bookseckill.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.bookseckill.entity.SeckillBook;
import com.example.bookseckill.entity.SeckillCurriculum;
import com.example.bookseckill.mapper.BooksMapper;
import com.example.bookseckill.service.SeckillSessionService;
import com.example.bookseckill.service.SeckillSkuRelationService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SeckillSessionServiceImpl extends ServiceImpl<BooksMapper, SeckillBook> implements SeckillSessionService {
    @Resource
    SeckillSkuRelationService seckillSkuRelationService;

    @Override
    public List<SeckillBook> getLates3DaySession() {
        //查出这3天参与秒杀的书
        List<SeckillBook> list = this.baseMapper.selectList(new QueryWrapper<SeckillBook>()
                .between("start_time",startTime(), endTime()));
        if (list !=null && list.size() > 0){
            List<SeckillBook> collect  = list.stream().map(seckillBook -> {
                Long id = seckillBook.getId();
                //查出关联id
                List<SeckillCurriculum> relationSkus = seckillSkuRelationService.list(new QueryWrapper<SeckillCurriculum>()
                        .eq("promotion_session_id", id));
                seckillBook.setRelationSkus(relationSkus);
                return seckillBook;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }

    /**
     * 当前时间
     * @return
     */
    private String startTime(){
        //获取当前日期
        LocalDate now = LocalDate.now();
        //获取最小时间
        LocalTime min = LocalTime.MIN;
        LocalDateTime start = LocalDateTime.of(now, min);
        //格式化时间
        String startFormat = start.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return startFormat;
    }

    /**
     * 结束时间
     * @return
     */
    private String endTime(){
        LocalDate now = LocalDate.now();
        LocalDate plus = now.plusDays(2);
        LocalTime max = LocalTime.MAX;
        LocalDateTime end = LocalDateTime.of(plus, max);
        //格式化时间
        String endFormat = end.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        return endFormat;

    }


}
